package com.open.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;
import net.sf.json.JSONObject;

public class IpInfo {
	public static String getIpInfo(String ip){
		String city="测试";
		JSONObject location=getLocation(ip);
        if (location != null && location.containsKey("code") && "0".equals(location.get("code").toString())) {
            JSONObject data = location.getJSONObject("data");
            if (data != null && data.containsKey("region_id") && data.containsKey("city_id")) {
		            city=data.getString("city");
            }
        }
		return city;
	}
	
	public static JSONObject getLocation(String ip) {
        JSONObject result = null;
        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
        try {
            String info = getHtml(url, "utf-8");
            if (StringUtils.isNotBlank(info)) {
                result = JSONObject.fromObject(info);
            }
        } catch (Exception e) {
        }
        return result;
    }
	
	
	static String getHtml(String url, String encode) throws HttpException, IOException {
        HttpClient client = new HttpClient();
        HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(2000);
        // 设置读数据超时时间(单位毫秒)
        managerParams.setSoTimeout(1000);
        GetMethod method = new GetMethod(url);
        client.executeMethod(method);
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        StringBuffer stringBuffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            stringBuffer.append(line);
        }
        String result = stringBuffer.toString();
        return result;
    }

}
